import { Context, Next } from 'koa';
import { verifyToken, extractTokenFromHeader } from '../utils/jwt';
import { ApiResponse, JwtPayload } from '../types';

// 认证中间件
export const authMiddleware = async (ctx: Context, next: Next) => {
  const token = extractTokenFromHeader(ctx.headers.authorization);
  
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      success: false,
      message: '请提供授权令牌'
    } as ApiResponse;
    return;
  }

  const payload = verifyToken(token);
  if (!payload) {
    ctx.status = 401;
    ctx.body = {
      success: false,
      message: '无效的授权令牌'
    } as ApiResponse;
    return;
  }

  ctx.state.user = payload;
  await next();
}; 